import cv2
def detect_displacement(targetPath, backgroundPath):
    # 读取目标图像和背景图像
    target = cv2.imread(targetPath, 0)
    background = cv2.imread(backgroundPath, 0)

    # 检查图像是否成功读取
    if target is None:
        print(f"无法读取目标图像: {targetPath}")
        return None
    if background is None:
        print(f"无法读取背景图像: {backgroundPath}")
        return None

    # 进行模板匹配
    result = cv2.matchTemplate(background, target, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

    # 获取匹配结果的左上角坐标
    top_left = max_loc

    return top_left


targetPath = 'D:/xiaowo1/target.png'
backgroundPath = 'D:/xiaowo1/background.png'
top_left = detect_displacement(targetPath, backgroundPath)
if top_left is not None:
    print(f"检测到的位移: {top_left}")

